import config from '@/config'
import {permissionCheck,phonePermissionSetting} from '@/utils/phonePermissionCheck'
import manifest from '@/manifest.json'
import upload, {pathToBase64} from '@/utils/upload'

function chooseImage(params) {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 1,
      sourceType: params && params.sourceType || ["camera"],
      crop:{
        quality: 80,
        width: 1080,
        height: 1440,
      },
      success: ({tempFilePaths}) => {
        if (Array.isArray(tempFilePaths) && tempFilePaths.length > 0) {
          resolve(tempFilePaths[0])
          return
        }
        if (typeof tempFilePaths === 'string' && !!tempFilePaths) {
          resolve(tempFilePaths)
          return
        }
        reject('选择图片失败')
      },
      fail: (err) => {reject(err)}
    })
  })
}

export default {
  data() {
    return {
      uploadState: {
        tempFilePath: '',
        params: {
          sourceType: ["camera"],
          isError: false,
        },
        maskInfo: {},
        updateCount: 0,
      },
    }
  },
  methods: {
    getPermission() {
      // #ifdef H5
      return Promise.resolve()
      // #endif

      //由于ios的机制问题，只有用过该功能它的权限列表才会出现该权限的设置,ios调用第一次就可直接打开相机
      // #ifndef H5
      return new Promise((resolve, reject) => {
        const iosFirstOpenCamera = this.$store.getters.iosFirstOpenCamera
        if (uni.getSystemInfoSync().platform === 'ios' && iosFirstOpenCamera) {
          this.$store.commit('SET_IOS_FIRST_OPEN_CAMERA', false)
          resolve()
          return
        }
        permissionCheck()
          .then(() =>{resolve()})
          .catch(err => {
            reject()
            uni.showModal({
              title: '手机权限',
              content: err,
              success: ({confirm}) => {
                if (confirm) {
                  phonePermissionSetting()
                }
              }
            });
          })
      })
      // #endif
    },

    async doChooseImageToBase64(arg = {params: {}, maskInfo: {}} , loadingShowFunc) {
      try {
        const params = arg?.params || {}
        const maskInfo = arg?.maskInfo || {}
        await this.getPermission()
        const tempFilePath = await chooseImage(params)
        if(loadingShowFunc){
          loadingShowFunc()
        }
        // h5直接使用bloburl作为图片路径
        // #ifdef H5
        const base64TempFilePath = tempFilePath
        // #endif
        // #ifndef H5
        const base64TempFilePath = await pathToBase64(tempFilePath)
        // #endif
        const uploadState = {
          tempFilePath: base64TempFilePath,
          params,
          maskInfo,
          updateCount: this.uploadState.updateCount + 1,
        }
        this.uploadState = uploadState
        return Promise.resolve(uploadState)
      } catch {
        const uploadState = {
          ...this.uploadState,
          tempFilePath: '',
          updateCount: this.uploadState.updateCount + 1,
        }
        this.uploadState = uploadState
        return Promise.reject(uploadState)
      }
    },
    doUploadImage(tempFilePath) {
      // 上传图片独立使用timeout,不使用全局timeout
      return upload({
        timeout:  10000,
        url: '/system/oss/upload',
        filePath: tempFilePath
      })
      // const timeOut = manifest.networkTimeout?.uploadFile || 1000
      // return new Promise((resolve, reject) => {
      //   const uploadTask = uni.uploadFile({
      //     url: config.baseUrl + '/system/oss/upload',
      //     filePath: tempFilePath,
      //     name: 'file',
      //     header: {
      //       Authorization: 'Bearer ' + this.$store.getters.token
      //     },
      //     success: (uploadFileRes) => {
      //       const data = JSON.parse(uploadFileRes.data)
      //       // 水印图片上传成功
      //       resolve(data)
      //     },
      //     fail: () => {
      //       //水印图片上传网络超时
      //       reject(tempFilePath)
      //     }
      //   })
      //   setTimeout(() => {
      //     uploadTask.abort()
      //   }, timeOut)
      // })
    },
  },
}
